﻿Shader "ProjectDanmaku/Entity"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags
        {
            "RenderType"="Opaque"
        }
        LOD 100

        Pass
        {
            Blend SrcAlpha OneMinusSrcAlpha
            
            CGPROGRAM
            #pragma enable_d3d11_debug_symbols
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 4.5

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float4 color : TEXCOORD1;
            };

            struct ShaderPropertyPerObject
            {
                float4 pos;
                float rot;
                int color;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            StructuredBuffer<ShaderPropertyPerObject> _ShaderPerEntityProperties;

            void rotate2D(inout float2 v, float r)
            {
                float s, c;
                sincos(r, s, c);
                v = float2(v.x * c - v.y * s, v.x * s + v.y * c);
            }

            float4 unpackColor(int color)
            {
                return float4(
                    ((color >> 24) & 0xff) / 255.0,
                    ((color >> 16) & 0xff) / 255.0,
                    ((color >> 8) & 0xff) / 255.0,
                    (color & 0xff) / 255.0);
            }
            
            v2f vert(appdata v, uint instance_id: SV_InstanceID)
            {
                v2f o;

                ShaderPropertyPerObject prop = _ShaderPerEntityProperties[instance_id];
                float4 wPos = prop.pos;

                rotate2D(v.vertex.xy, prop.rot);
                
                o.vertex = mul(UNITY_MATRIX_VP, v.vertex + wPos);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.color = unpackColor(prop.color);

                o.vertex.z = 0.5f;
                
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                
                return col * i.color;
            }
            ENDCG
        }
    }
}